import 'package:dio/dio.dart';
import 'package:flutter_common_utils/common_utils_export.dart';
import 'package:flutter_base_app/config/i18n/i18n.dart';
import 'package:flutter_base_app/constant/sp_key.dart';
import 'package:flutter_base_app/utils/channel/app_type.dart';
import 'package:flutter_base_app/utils/http/http_code.dart';
import 'package:flutter_base_app/utils/user/user_help.dart';
import 'package:flutter_live_data/live_data_export.dart';
import 'package:flutter_http_utils/flutter_http_utils.dart';
import '../../constant/event_bus_key.dart';
import '../../generated/json/base/json_convert_content.dart';
import '../../model/base/json_convert.dart';
import '../../router/routes_manager.dart';
import 'Interceptors.dart';
import 'http_proxy.dart';

/// 项目的http相关的配置信息
class HttpManager {
  //正式环境，注解使用 http://18.184.22.18:8060
  static const URL_PROD = "https://ebike-api.vinkacloud.com";

  // static const URL_PROD = "https://ebike-api-dev.vinkacloud.com";

  //测试环境，注解使用
  static const URL_TEST = "https://ebike-api-dev.vinkacloud.com";
  static var _BASE_URL = "";

  static String get BASE_URL => _BASE_URL;
  static const String BASE_PATH = "/api";
  static HttpManager? _instance;

  static void init() {
    initBaseHost();
    HttpUtils.getDio = () => dio;
    HttpUtils.createUrl = createUrl;
    HttpUtils.fromJsonAsT = JsonConvert.fromJsonAsT;
    HttpUtils.handleResult = handleResult;
  }

  static HttpManager getInstance() {
    _instance ??= HttpManager._internal();
    return _instance!;
  }

  static Dio get dio => getInstance()._dio!;

  // 私有构造函数
  HttpManager._internal() {
    AppJsonConvert.init();
    _createDio();
    EventBusKey.LOGIN.busForever((it) {
      setCommonParams();
    });
    EventBusKey.EXIT_LOGIN.busForever((it) {
      setCommonParams();
    });
    EventBusKey.LANGUAGE_CHANGE.busForever((it) {
      _dio!.options.headers["Vinka-App-Language"] = I18nConfig.locale.languageCode;
    });
    EventBusKey.HTTP_PROXY_CHANGE.busForever((it) {
      getInstance()._createDio();
    });
  }

  Dio? _dio;

  Dio _createDio() {
    _dio = Dio(BaseOptions(
      contentType: 'application/json',
      receiveTimeout: const Duration(seconds: 20),
      connectTimeout: const Duration(seconds: 20),
      sendTimeout: const Duration(seconds: 20),
//      baseUrl: Config.BASE_URL,
    ));
    setCommonParams();
    _dio!.interceptors.add(LoggingInterceptor());
    _dio!.interceptors.add(RefreshTokenInterceptor());
    HttpProxy.startSet(_dio!);
    return _dio!;
  }

  void setCommonParams() {
    _dio!.options.headers = {
      "appType": 'flutter',
      "uid": UserHelp.userData?.userId,
      "accessToken": UserHelp.userData?.token,
      "os": AppUtils.platform,
      "osBrand": AppUtils.getBrand(),
      "osVersion": AppUtils.getOSVersion(),
      "devid": AppUtils.getDeviceId(),
      "appVersion": AppUtils.version,
      "appVersionCode": AppUtils.versionCode,
      "Vinka-App-Language": I18nConfig.locale.languageCode,
      "Vinka-Zone": AppUtils.getTimeZone(),
      "brandID": appType.code,
      // "Vinka-import 'package:timezone/timezone.dart' as tz;": AppUtils.version,
    };
  }

  //处理逻辑
  static handleResult(HttpResponse data, {AbsHttpUiHandler? handle}) {
    if (data.isSucceed) {
      return;
    }
    if (data.code == HttpCodeApp.AUTH_ERROR || data.code == HttpCodeApp.NO_LOGIN) {
      UserHelp.cleanData();
      RouterJump.login();
    }
  }

  //创建Url
  static String createUrl({String? path}) {
    if (path != null && path.startsWith(HttpManager.BASE_PATH)) {
      return "${HttpManager.BASE_URL}$path";
    }
    return "${HttpManager.BASE_URL}${BASE_PATH + (path ?? "")}";
  }

  static void initBaseHost() {
    //调试使用
    // if (AppUtils.isDebug) {
    //   BASE_URL = URL_TEST;
    //   return;
    // }
    if (SpKey.BASE_URL_TYPE.storeContains()) {
      final sp = SpKey.BASE_URL_TYPE.getIntStore(def: 2);
      if (sp == 1) {
        _BASE_URL = URL_TEST;
        return;
      }
      if (sp == 2) {
        _BASE_URL = URL_PROD;
        return;
      }
    }
    _BASE_URL = (AppUtils.isBeta || AppUtils.isDebug) ? URL_TEST : URL_PROD;
  }
}
